// @algorithm @lc id=100307 lang=javascript
// @title xu-lie-hua-er-cha-shu-lcof
/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */

/**
 * Encodes a tree to a single string.
 *
 * @param {TreeNode} root
 * @return {string}
 */
var serialize = function (root) {
  if (root === null) return 'null';
  const queue = [];
  const ans = [];
  queue.push(root);

  while (queue.length) {
    const node = queue.shift();
    if (node === null) {
      ans.push('null');
    } else {
      ans.push(node.val);
      queue.push(node.left ? node.left : null);
      queue.push(node.right ? node.right : null);
    }
  }
  return ans.join(',');
};

/**
 * Decodes your encoded data to tree.
 *
 * @param {string} data
 * @return {TreeNode}
 */
var deserialize = function (data) {
  if (data === 'null') return null;
  const arr = data.split(',');
  const root = new TreeNode(Number(arr[0]));
  const queue = [root];
  let i = 1;
  while (queue.length) {
    const node = queue.shift();
    if (arr[i] !== 'null') {
      node.left = new TreeNode(Number(arr[i]));
      queue.push(node.left);
    }
    i++;
    if (arr[i] !== 'null') {
      node.right = new TreeNode(Number(arr[i]));
      queue.push(node.right);
    }
    i++;
  }
  return root;
};

/**
 * Your functions will be called as such:
 * deserialize(serialize(root));
 */
